package com.googlecode.garbagecan.asmstudy.classloader;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class CustomClassLoader extends ClassLoader {

	public CustomClassLoader(ClassLoader parent) {
		super(parent);
	}

	private Class<?> getClass(String name) throws ClassNotFoundException {
		String file = name.replace('.', File.separatorChar) + ".class";
		byte[] bytes = null;
		try {
			bytes = loadClassData(file);
			Class<?> c = defineClass(name, bytes, 0, bytes.length);
			resolveClass(c);
			return c;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		System.out.println("loading class '" + name + "'");
		if (name.startsWith("com.googlecode.garbagecan.asmstudy.classloader.")) {
			return getClass(name);
		}
		return super.loadClass(name);
	}

	private byte[] loadClassData(String name) throws IOException {
		InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
		int size = stream.available();
		byte bytes[] = new byte[size];
		DataInputStream in = new DataInputStream(stream);
		in.readFully(bytes);
		in.close();
		return bytes;
	}
}
